<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/12
 * Time: 9:36
 */
namespace App\Http\Controllers\Api\V4;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator, DB;
use App\Modules\EntPushMoneyLog;
use App\Modules\EntMemberDRP;
use App\Modules\EntMemberInfo;
use App\Modules\EntWithdrawMoneyLog;
use App\Modules\EntPayCard;
use App\Modules\EntMobileCode;
use App\Modules\EntPosterTemplate;
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;

use App\Common\MobileMassege;
use App\Models\V1\PartnerModel;

class MemberDRPController extends BaseController
{
    protected $url;
    protected $urlapi;
    protected $url2;
    protected $bankname = ['中国工商银行', '招商银行', '交通银行', '中国银行', '中国农业银行', '中国邮政储蓄银行', '中国建设银行'];
    protected $address = ['陈亮', '上海市徐汇区龙漕路299号天华信息科技园3B楼8层', '上海小南瓜生活信息科技有限公司'];
    protected $expName = ['圆通速递', '申通快递', '韵达速递', '中通快递', '顺丰速运', 'EMS', '天天快递', '全峰快递', '宅急送', '百世快递'];

    public function __construct(){
        $this->url      = env('ADMIN_HOST');
        $this->url2     = $this->url;
        $this->urlapi   = env('API_HOST');
    }

    public function memDRPDetail(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'key' => 'required'
        ];
        $messages = [
            'mobile.required'   => '2037',
            'key.required'      => '2038'
        ];
        $mobile = $request->input('mobile');
        $key    = $request->input('key');
        $params = ['mobile' => $mobile, 'key' => $key];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $partnerModel   = new PartnerModel();
        $partnerInfo    = $partnerModel->get_partner_info($mobile,$key);

        //会员不存在
        if(!$partnerInfo){
            return response()->json(['message' => $result, 'code' => '3029']);//会员信息不存在
        }

        //会员不是合伙人
        if(!isset($partnerInfo->DRPID)){
            return response()->json(['message' => $result, 'code' => '3030']);//合伙人信息不存在
        }


        //合伙人详细 isRebater 是否开始回扣   以下memMoney是收益金额
        if ($partnerInfo->IsRebate == 0) {  //没有回扣 金额等于
            $memMoney = $partnerInfo->SalesMoney;
        } else {
            $memMoney = $partnerInfo->MemBalances;
        }

        $drpDetail = [
            'YourName'  => $partnerInfo->YourName,
            'FilePath1' => $partnerInfo->FilePath1,
            'MemMoney'  => $memMoney
        ];
        /**
         * 7天的销售情况--开始
         */
        $timeMax = date('Y-m-d', time());
        $timeMin = date("Y-m-d", strtotime("-6 day"));
        $entPushMoneyLog = EntPushMoneyLog::select('AddDate')
            ->where('MemNumber', $partnerInfo->MemNumber)
            ->whereDate('AddDate', '>=', $timeMin)
            ->whereDate('AddDate', '<=', $timeMax)
            ->get();

        $arrayWeekCount = [];
        for ($i = 1; $i < 8; $i++) 
        {
            $d = date("Y-m-d", strtotime(($i - 7) . " day"));
            $d = base64_encode($d);
            $arrayWeekCount[$d] = 0;
        }

        if (count($entPushMoneyLog) > 0) 
        {
            foreach ($entPushMoneyLog as $key) 
            {
                $addDate = date('Y-m-d', strtotime($key->AddDate));
                $addDate = base64_encode($addDate);
                if (array_key_exists($addDate, $arrayWeekCount)) 
                {
                    $arrayWeekCount[$addDate] = $arrayWeekCount[$addDate] + 1;

                }
            }
        }
        $timearray = array();
        $maxarray = array();
        foreach ($arrayWeekCount as $k => $v) {
            $k = base64_decode($k);
            $timearray[] = $k;
            $maxarray[] = $v;
        }
        /**
         * 7天的销售情况--结束
         */
        return response()->json(['message' => 'ok', 'code' => '200', 'drpdetail' => $drpDetail, 'time' => $timearray, 'number' => $maxarray]);

    }

    /**
     * 佣金和提现记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function commission(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'key' => 'required'
        ];
        $messages = [
            'mobile.required' => '2037',
            'key.required' => '2038'
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $params = ['mobile' => $mobile, 'key' => $key];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $entMemberInfo = $this->memNumber($mobile, $key);
        if ($entMemberInfo) {
            $entMemberDRP = EntMemberDRP::select('FinishMoney', 'SalesMoney', 'DRPID', 'IsRebate', 'MemBalances')
                ->where('MemNumber', $entMemberInfo->MemNumber)
                ->where('DeleteMark', 1)
                ->first();

            if ($entMemberDRP) {
                $memMoney = 0; //佣金显示
                if ($entMemberDRP->IsRebate == 0) {
                    $memMoney = $entMemberDRP->SalesMoney;
                } else {
                    $memMoney = $entMemberDRP->MemBalances;
                }
                //提现记录
                $entWithdrawMoneyLog = EntWithdrawMoneyLog::select('CardNo', 'States', 'WithdrawRemark', 'WithdrawMoney', 'AddDate')
                    ->where('MemNumber', $entMemberInfo->MemNumber)
                    ->orderBy('AddDate', 'desc')
                    ->get();
                //提成记录
                $entPushMoneyLog = DB::table('vw_web_pushmoneylog')
                    ->select('PuMoID', 'MemNumber', 'Scale', 'IsFinish', 'TotalMoney', 'SalesMoney', 'PayMoney', 'MemberType', 'YourName', 'AddDate')
                    ->where('MemNumber', $entMemberInfo->MemNumber)
                    ->where('DeleteMark', '1')
                    ->orderBy('AddDate', 'desc')
                    ->get();

                $firstid = EntPushMoneyLog::select('PuMoID')
                    ->where('IsFinish', 1)
                    ->where('MemNumber', $entMemberInfo->MemNumber)
                    ->orderBy('AddDate', 'asc')
                    ->first();

                $id = 0;
                if ($firstid) {
                    $id = $firstid->PuMoID;
                }
                //提现账号验证
                $entPayCard = EntPayCard::select('BankType', 'CardNo', 'PayType')
                    ->where('IsDefault', 1)
                    ->where('DeleteMark', 1)
                    ->where('MemNumber', $entMemberInfo->MemNumber)
                    ->first();

                if (!$entPayCard) {
                    $entPayCard = '0';
                } else {
                    $entPayCard = '1';
                }

                $pushMoneydataList = array();
                $pushMoneyCollect = collect($pushMoneydataList);
                if (count($entPushMoneyLog) > 0) {

                    //提成记录lt--左上 ln--左下 rt--右上 rn--右下 rc1--中间 rc2--中间
                    foreach ($entPushMoneyLog as $pushMoneydata) {
                        if ($pushMoneydata->IsFinish == 0) {
                            if ($pushMoneydata->Scale == '0.05') {
                                $pushMoneydataList['lt'] = '任务';
                                if ($pushMoneydata->MemberType == 1) {
                                    $pushMoneydataList['ln'] = '下线合伙人“' . $pushMoneydata->YourName . '”发展新合伙人';
                                } else {
                                    $pushMoneydataList['ln'] = '下线合伙人“' . $pushMoneydata->YourName . '”发展新会员';
                                }
                                $pushMoneydataList['rt'] = '完成金额 ￥' . $pushMoneydata->TotalMoney;
                                $pushMoneydataList['rc1'] = '';
                                $pushMoneydataList['rc2'] = '';
                                $pushMoneydataList['rn'] = $pushMoneydata->AddDate;
                            } else {
                                $pushMoneydataList['lt'] = '任务';
                                if ($pushMoneydata->MemberType == 1) {
                                    $pushMoneydataList['ln'] = '发展“' . $pushMoneydata->YourName . '”成为了会员';
                                } else {
                                    $pushMoneydataList['ln'] = '发展“' . $pushMoneydata->YourName . '”成为了合伙人';
                                }
                                $pushMoneydataList['rt'] = '完成金额 ￥' . $pushMoneydata->TotalMoney;
                                $pushMoneydataList['rc1'] = '';
                                $pushMoneydataList['rc2'] = '';
                                $pushMoneydataList['rn'] = $pushMoneydata->AddDate;
                            }
                        } else {
                            if ($pushMoneydata->Scale == '0.05') {
                                $pushMoneydataList['lt'] = '销售';
                                if ($pushMoneydata->MemberType == 1) {
                                    $pushMoneydataList['ln'] = '下线合伙人“' . $pushMoneydata->YourName . '”发展新会员';
                                } else {
                                    $pushMoneydataList['ln'] = '下线合伙人' . $pushMoneydata->YourName . '”发展新合伙人';
                                }
                                $pushMoneydataList['rt'] = '提成 +' . $pushMoneydata->TotalMoney;
                                $pushMoneydataList['rc1'] = '';
                                $pushMoneydataList['rc2'] = '';
                                $pushMoneydataList['rn'] = $pushMoneydata->AddDate;
                            } else {
                                if ($pushMoneydata->PuMoID == $id) {
                                    $u = $pushMoneydata->TotalMoney - $entMemberDRP->SalesMoney;
                                    $ul = $pushMoneydata->TotalMoney - $u;
                                    $pushMoneydataList['lt'] = '销售';
                                    if ($pushMoneydata->MemberType == 1) {
                                        $pushMoneydataList['ln'] = '发展“' . $pushMoneydata->YourName . '”成为了会员';
                                    } else {
                                        $pushMoneydataList['ln'] = '发展“' . $pushMoneydata->YourName . '”成为了合伙人';
                                    }
                                    $pushMoneydataList['rt'] = '完成金额 +' . $ul;
                                    $pushMoneydataList['rc1'] = '提成 +' . $pushMoneydata->PayMoney;
                                    $pushMoneydataList['rc2'] = '超出任务' . $pushMoneydata->TotalMoney - $entMemberDRP->SalesMoney;
                                    $pushMoneydataList['rn'] = $pushMoneydata->AddDate;
                                } else {
                                    $pushMoneydataList['lt'] = '销售';
                                    if ($pushMoneydata->MemberType == 1) {
                                        $pushMoneydataList['ln'] = '发展“' . $pushMoneydata->YourName . '”成为了会员';
                                    } else {
                                        $pushMoneydataList['ln'] = '发展“' . $pushMoneydata->YourName . '”成为了合伙人';
                                    }
                                    $pushMoneydataList['rt'] = '提成 +' . $pushMoneydata->TotalMoney;
                                    $pushMoneydataList['rc1'] = '';
                                    $pushMoneydataList['rc2'] = '';
                                    $pushMoneydataList['rn'] = $pushMoneydata->AddDate;
                                }
                            }
                        }
                        $pushMoneyCollect->push($pushMoneydataList);
                    }

                    $str = $pushMoneyCollect->all();
                }
                //提现记录
                if (count($entWithdrawMoneyLog) > 0) {
                    foreach ($entWithdrawMoneyLog as $withdrawMoneydata) {
                        if ($withdrawMoneydata->States == 2) {
                            $pushMoneydataList['lt'] = '提现失败返还';
                            $pushMoneydataList['ln'] = '备注' . $withdrawMoneydata->WithdrawRemark;
                            $pushMoneydataList['rt'] = '金额 ' . $withdrawMoneydata->WithdrawMoney;
                            $pushMoneydataList['rc1'] = '';
                            $pushMoneydataList['rc2'] = '';
                            $pushMoneydataList['rn'] = $withdrawMoneydata->AddDate;
                            $pushMoneyCollect->push($pushMoneydataList);
                            $pushMoneydataList['lt'] = '提现[失败]';
                            $pushMoneydataList['ln'] = '';
                            $pushMoneydataList['rt'] = '- ' . $withdrawMoneydata->WithdrawMoney;
                            $pushMoneydataList['rc1'] = '账户' . '*****' . substr($withdrawMoneydata->CardNo, -4);
                            $pushMoneydataList['rc2'] = '';
                            $pushMoneydataList['rn'] = $withdrawMoneydata->AddDate;
                            $pushMoneyCollect->push($pushMoneydataList);
                        } else {
                            if ($withdrawMoneydata->States == 0) {
                                $pushMoneydataList['lt'] = '提现 [处理中]';
                                $pushMoneydataList['ln'] = '';
                                $pushMoneydataList['rt'] = '金额 ' . $withdrawMoneydata->WithdrawMoney;
                                $pushMoneydataList['rc1'] = '账户' . '*****' . substr($withdrawMoneydata->CardNo, -4);
                                $pushMoneydataList['rc2'] = '';
                                $pushMoneydataList['rn'] = $withdrawMoneydata->AddDate;
                            } else {
                                $pushMoneydataList['lt'] = '提现 [提现成功]';
                                $pushMoneydataList['ln'] = '';
                                $pushMoneydataList['rt'] = '金额 ' . $withdrawMoneydata->WithdrawMoney;
                                $pushMoneydataList['rc1'] = '账户' . '*****' . substr($withdrawMoneydata->CardNo, -4);
                                $pushMoneydataList['rc2'] = '';
                                $pushMoneydataList['rn'] = $withdrawMoneydata->AddDate;
                            }
                            $pushMoneyCollect->push($pushMoneydataList);
                        }

                    }
                }
                $sorted = $pushMoneyCollect->sortByDesc('rn');
                $str = $sorted->values()->all();
                return response()->json([
                    'message' => 'ok',
                    'code' => '200',
                    'ispaycard' => $entPayCard,
                    'memdrpdetail' => $entMemberDRP,
                    'withdrawmoneylist' => $entWithdrawMoneyLog,
                    'pushmoneylist' => $str,
                    'memmoney' => $memMoney,
                    'id' => $id]);
            } else {
                return response()->json(['message' => $result, 'code' => '3030']);//合伙人信息不存在
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3029']);//会员信息不存在
        }
    }

    /**
     * 提现卡号列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function paycard(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'key' => 'required'
        ];
        $messages = [
            'mobile.required' => '2037',
            'key.required' => '2038'
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $params = ['mobile' => $mobile, 'key' => $key];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $entMemberInfo = $this->memNumber($mobile, $key);
        if ($entMemberInfo) {
            $entPayCard = EntPayCard::select('PaCaID', 'BankType', 'PayType', 'CardNo', 'IsDefault')->where('DeleteMark', '1')->where('MemNumber', $entMemberInfo->MemNumber)->get();
            if (count($entPayCard) > 0) {
                foreach ($entPayCard as $data) {
                    if ($data->PayType == 1) {
                        $data->PayType = $this->bankname[$data->BankType];
                    } else {
                        $data->PayType = '支付宝';
                    }
                }
            }
        }
        return response()->json(['message' => 'ok', 'code' => '200', 'paycardlist' => $entPayCard]);
    }

    /**
     * 添加银行卡
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bankPayCardStore(Request $request)
    {
        $payType = 1;
        $bankName = $request->input('banktype');
        $userName = $request->input('yourname');
        $code = false;
        if(empty($bankName)){
            $code = '2050';
            $msg = "银行类型为空";
        }elseif(empty($userName)){
            $code = '2049';
            $msg  = "用户名为空";
        }
        if($code){
            return response()->json(['message' => $msg, 'code' => $code]);
        }
        return $this->add_pay_card($request,$payType);
    }


    /**
     * 添加支付宝账号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function aliPayCardStore(Request $request)
    {
        $payType = 2;
        return $this->add_pay_card($request,$payType);
    }


    /**
     * 添加支付账号
     * */
    public function add_pay_card($request,$type){
        $result = 'no';
        $rules = [
            'cardno'    => 'required',
            'mobile'    => 'required',
            'code'      => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages = [
            'cardno.required'   => '2051',
            'mobile.required'   => '2045',
            'code.required'     => '2052',
            'key.required'      => '2046',
            'timestamp.required'=> '2047',
            'sign.required'     => '2048'
        ];
        $securitycode   = $request->input('code');
        $cardno         = $request->input('cardno');
        $mobile         = $request->input('mobile');
        $key            = $request->input('key');
        $sign           = $request->input('sign');
        $timestamp      = $request->input('timestamp');

        $params = [
            'mobile'    => $mobile,
            'key'       => $key,
            'cardno'    => $cardno,
            'code'      => $securitycode,
            'timestamp' => $timestamp,
            'sign'      => $sign];

        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }


        $partnerMordel  = new PartnerModel();
        $partnerInfo    = $partnerMordel->get_partner_info($mobile,$key);
        if(!$partnerInfo){
            //合伙人信息读取失败
            return response()->json(['message' => $result, 'code' => '3031']);
        }

        //验证校验码是否正确
        $messageModel   = new MobileMassege();
        $result         = $messageModel->check_valid_code($mobile,$securitycode);
        if($result == false){
            //return response()->json(['message' => $result, 'code' => '3037']);
        }

        $data = [
            'PayType'   => $type,
            'MemNumber' =>$partnerInfo->MemNumber,
            'CardNo'    => $cardno,
            'BankType'  => $request->input('banktype')?$request->input('banktype'):'',
            'YourName'  => $request->input('yourname')?$request->input('yourname'):'',
            'DeleteMark'=> 1,
            'ReleaseDate'=>date_time(),
            'AddDate'   => date_time()
        ];

        $result = $partnerMordel->add_pay_card($data);
        if ($result) {
            return response()->json(['message' => 'ok', 'code' => '200']); //卡号添加失败
        } else {
            return response()->json(['message' => $result, 'code' => '3032']);//卡号添加失败
        }
    }



    /**
     * 读取所有银行
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBankName(Request $request)
    {
        return response()->json(['message' => 'ok', 'code' => '200', 'banknamelist' => $this->bankname]);
    }

    /**
     * 发送短信
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addMobCode(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'type' => 'required'
        ];
        $messages = [
            'mobile.required' => '2037',
            'type.required' => '2038'
        ];

        $usermobile     = $request->input('mobile');
        $type           = $request->input('type');
        $params         = ['mobile' => $usermobile, 'type' => $type];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if(empty($usermobile)){
            return response()->json(['message' => $result, 'code' => '3003']);
        }

        $mobileMessage  = new MobileMassege();

        if($mobileMessage->check_can_send_code($usermobile) == false){ // 距离上次的发送时间太短
            return response()->json(['message' => $result, 'code' => '3010']);
        }

        $code = randStr(6);
        if($type == 2){
            $msg = '校验码' . $code . '，您在老侯代读正在提交提现申请，请勿告诉别人哦！';
        }elseif($type == 1){
            $msg = '校验码' . $code . '，您在老侯代读正在提交绑定银行卡申请，请勿告诉别人哦！';
        }

        $mobileMessage->code    = $code;
        $mobileMessage->codeMsg = $msg;
        $result = $mobileMessage->send_valid_code();
        if($result == true){
            return response()->json(['message' => 'ok', 'code' => '200']);
        }else{
            return response()->json(['message' => "短信发送失败", 'code' => '3009']);
        }
    }




    /**
     * 设置默认账号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upPayCardDefault(Request $request)
    {
        $result = 'no';
        $rules = [
            'id' => 'required',
            'mobile' => 'required',
            'key' => 'required',
            'timestamp' => 'required',
            'sign' => 'required'
        ];
        $messages = [
            'id.required' => '2039',
            'mobile.required' => '2037',
            'key.required' => '2038',
            'timestamp.required' => '2047',
            'sign.required' => '2048'
        ];
        $id = $request->input('id');
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $sign = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params = ['mobile' => $mobile, 'key' => $key, 'id' => $id, 'timestamp' => $timestamp, 'sign' => $sign];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        if ($this->checkSign($params) == true) {
            $member = $this->memNumber($mobile, $key);
            if ($member) {
                DB::beginTransaction();
                try {
                    DB::table('PayCard')->where('MemNumber', $member->MemNumber)->update(['IsDefault' => 0]);
                    DB::table('PayCard')->where('MemNumber', $member->MemNumber)->where('PaCaID', $id)->update(['IsDefault' => 1]);
                    return response()->json(['message' => 'ok', 'code' => '200']);
                    DB::commit();
                } catch (Exception $e) {
                    DB::rollBack();
                    return response()->json(['message' => $result, 'code' => '3034']);
                }
            } else {
                //合伙人信息读取失败
                return response()->json(['message' => $result, 'code' => '3035']);
            }
        } else {
            //签名错误
            return response()->json(['message' => $result, 'code' => '3036']);
        }
    }

    /**
     * 提现申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function withdrawMoneyStore(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'key' => 'required',
            'code' => 'required',
            'cardno' => 'required',
            'bankname' => 'required',
            'money' => 'required',
            'expressname' => 'required',
            'expressnumber' => 'required',
            'timestamp' => 'required',
            'sign' => 'required'
        ];
        $messages = [
            'mobile.required' => '2053',
            'key.required' => '2054',
            'code.required' => '2055',
            'cardno.required' => '2056',
            'bankname.required' => '2057',
            'money.required' => '2059',
            'expressname.required' => '2060',
            'expressnumber.required' => '2061',
            'timestamp.required' => '2062',
            'sign.required' => '2063'
        ];

        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $securitycode = $request->input('code');
        $cardno = $request->input('cardno');
        $bankname = $request->input('bankname');
        $money = $request->input('money');
        $expressname = $request->input('expressname');
        $expressnumber = $request->input('expressnumber');
        $sign = $request->input('sign');
        $timestamp = $request->input('timestamp');

        $params = ['mobile' => $mobile, 'key' => $key, 'code' => $securitycode, 'cardno' => $cardno, 'bankname' => $bankname, 'money' => $money, 'expressname' => $expressname, 'expressnumber' => $expressnumber, 'timestamp' => $timestamp, 'sign' => $sign];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) == true) {
            //验证校验码是否正确
            $mobileCode = EntMobileCode::select('ID')->where('Mobile', $mobile)
                ->where('States', 1)
                ->where('Code', $securitycode)
                ->first();
            if ($mobileCode) {
                $member = $this->memNumber($mobile, $key);
                if ($member) {
                    $entMemberDRP = $this->memDRPNumber($member->MemNumber);
                    if ($entMemberDRP) {
                        //会员银行卡验证
                        $entPayCard = $this->memPayCard($cardno, $member->MemNumber);
                        if ($entPayCard) {
                            //抵扣合伙人金额
                            $memBalances = $entMemberDRP->MemBalances - $money;
                            if ($memBalances >= 0) {
                                DB::beginTransaction();
                                try {
                                    $entWithdrawMoneyLog = new EntWithdrawMoneyLog();
                                    $entWithdrawMoneyLog->States = 0;
                                    $entWithdrawMoneyLog->MemNumber = $member->MemNumber;
                                    $entWithdrawMoneyLog->InvoiceTitle = $this->address[2];
                                    $entWithdrawMoneyLog->CardNo = $cardno;
                                    $entWithdrawMoneyLog->BankName = $bankname;
                                    $entWithdrawMoneyLog->YourName = $entPayCard->YourName;
                                    $entWithdrawMoneyLog->WithdrawMoney = $money;
                                    $entWithdrawMoneyLog->ExpressName = $expressname;
                                    $entWithdrawMoneyLog->ExpressNumber = $expressnumber;
                                    $entWithdrawMoneyLog->DeleteMark = 1;
                                    $entWithdrawMoneyLog->WithdrawRemark = '';
                                    $entWithdrawMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                                    $entWithdrawMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                                    $entWithdrawMoneyLog->save();
                                    if ($entWithdrawMoneyLog) {
                                        EntMemberDRP::where('MemNumber', $member->MemNumber)->where('DeleteMark', 1)->update(['MemBalances' => $memBalances]);
                                        EntMobileCode::where('Mobile', $mobile)->where('States', 1)->delete();
                                        return response()->json(['message' => 'ok', 'code' => '200']);
                                    } else {
                                        //申请失败
                                        return response()->json(['message' => $result, 'code' => '3040']);
                                    }
                                    DB::commit();
                                } catch (Exception $e) {
                                    DB::rollBack();
                                    //申请失败
                                    return response()->json(['message' => $result, 'code' => '3041']);
                                }
                            } else {
                                //余额不足
                                return response()->json(['message' => $result, 'code' => '3042']);
                            }
                        } else {
                            //读取卡号信息失败
                            return response()->json(['message' => $result, 'code' => '3047']);
                        }

                    } else {
                        //合伙人信息读取失败
                        return response()->json(['message' => $result, 'code' => '3043']);
                    }
                } else {
                    //会员信息读取失败
                    return response()->json(['message' => $result, 'code' => '3044']);
                }
            } else {
                //验证码不正确
                return response()->json(['message' => $result, 'code' => '3045']);
            }
        } else {
            //签名错误
            return response()->json(['message' => $result, 'code' => '3046']);
        }
    }

    /**
     * 我的好友
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function memFriendList(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'key' => 'required'
        ];
        $messages = [
            'mobile.required' => '2037',
            'key.required' => '2038'
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $params = ['mobile' => $mobile, 'key' => $key];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $entMemberInfo = $this->memNumber($mobile, $key);
        if ($entMemberInfo) {
            $entMemberDRP = EntMemberDRP::select('DRPID')->where('MemNumber', $entMemberInfo->MemNumber)->where('DeleteMark', 1)->first();
            if ($entMemberDRP) {
                $friends = DB::table('VW_WEB_memberdrp')->select('YourName', 'UserName', 'FilePath1', 'AddDate', 'DRPLevel', 'States', 'YourName as TypeName')->where('ParentID', $entMemberDRP->DRPID)->get();
                foreach ($friends as $data) {
                    if ($data->States == 0) {
                        $data->TypeName = '非会员';
                    } else {
                        switch ($data->DRPLevel) {
                            case 1:
                                $data->TypeName = '学习官';
                                break;
                            case 2:
                                $data->TypeName = '会员';
                                break;
                        }
                    }
                }
                return response()->json(['message' => 'ok', 'code' => '200', 'friendlist' => $friends]);
            } else {
                return response()->json(['message' => $result, 'code' => '3030']);//合伙人信息不存在
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3029']);//会员信息不存在
        }
    }

    /**
     * 提现发票信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function invoiceInfo(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'key' => 'required'
        ];
        $messages = [
            'mobile.required' => '2037',
            'key.required' => '2038'
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $params = ['mobile' => $mobile, 'key' => $key];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $entMemberInfo = $this->memNumber($mobile, $key);
        if ($entMemberInfo) {
            $entMemberDRP = $this->memDRPNumber($entMemberInfo->MemNumber);
            if ($entMemberDRP) {
                return response()->json(['message' => 'ok', 'code' => '200', 'address' => $this->address, 'expname' => $this->expName, 'money' => $entMemberDRP->MemBalances]);
            } else {
                return response()->json(['message' => $result, 'code' => '3039']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3038']);
        }
    }

    /**
     * 默认模板
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function defaultTemplate(Request $request)
    {
        $url = $this->url;
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'key' => 'required'
        ];
        $messages = [
            'mobile.required' => '2037',
            'key.required' => '2038'
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $params = ['mobile' => $mobile, 'key' => $key];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        $entMemberInfo = $this->memNumber($mobile, $key);
        if ($entMemberInfo) {
            $entMemberDRP = EntMemberDRP::select('DRPID')->where('MemNumber', $entMemberInfo->MemNumber)->where('DeleteMark', 1)->first();
            if ($entMemberDRP) {
                //所有模板图片
                $entPosterTemplate = EntPosterTemplate::select('PoTeID', 'PosterTitle', 'FilePath1', 'AddDate')
                    ->where('IsShow', '1')
                    ->where('DeleteMark', '1')
                    ->orderBy('ReleaseDate', 'desc')
                    ->get();


                $tempurl    = "";
                //模板文件
                foreach ($entPosterTemplate as $key => $data) {

                    $file = public_path($data->FilePath1);

                    if(!@fopen($file,'r')){ //模板图片不存在
                        unset($entPosterTemplate->$key);
                        continue;
                    }

                    $extendImg  = "/uploads/posttemp/".$entMemberInfo->MemNumber."_".$data->PoTeID.".png";
                    if(!@fopen($extendImg,'r')){  //宣传图片不存在

                        //海报模板
                        $img1 = imageCreateFromPng($file);

                        //会员二维码
                        $qrimg = public_path('/uploads/qrcode/' . $entMemberInfo->MemNumber . '.png');
                        $img2 = imageCreateFromPng($qrimg);


                        imagecopymerge($img1, $img2, 205, 400, 0, 0, imagesx($img2), imagesy($img2), 100);
                        imagepng($img1, public_path($extendImg));
                        imagedestroy($img1);
                    }
                    $data->FilePath1 = $this->url . $extendImg;
                    if(!$tempurl){
                        $tempurl = $data->FilePath1;
                    }
                }

                //默认模板
                /*
                $tempimg = $url . '/uploads/posttemp/' . $entMemberInfo->MemNumber . '.png';
                if (@fopen($tempimg, 'r')) {
                    $isImg = 1;
                } else {
                    $tempimg2 = $this->url2 . '/uploads/posttemp/' . $entMemberInfo->MemNumber . '.png';
                    if (@fopen($tempimg2, 'r')) {
                        $isImg = 2;
                    } else {
                        $isImg = 0;
                    }
                }
                $tempurl = '';
                switch ($isImg) {
                    case 0:
                        $tempurl = $this->urlapi . $this->shareimgStore($entMemberInfo->MemNumber);
                        break;
                    case 1:
                        $tempurl = $url . '/uploads/posttemp/' . $entMemberInfo->MemNumber . '.png';
                        break;
                    case 2:
                        $tempurl = $this->url2 . '/uploads/posttemp/' . $entMemberInfo->MemNumber . '.png';
                        break;
                }*/


                return response()->json(['message' => 'ok', 'code' => '200', 'postertemplist' => $entPosterTemplate, 'tempurl' => $tempurl]);
            } else {
                return response()->json(['message' => $result, 'code' => '3030']);//合伙人信息不存在
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3029']);//会员信息不存在
        }
    }

    protected function shareimgStore($memNumber = '')
    {

        $url = '';
        try {
            //获取第一个模板
            $entPosterTemplate = EntPosterTemplate::select('PosterTitle', 'FilePath1', 'PoTeID')->where('DeleteMark', 1)->where('IsShow', 1)->orderBy('ReleaseDate', 'desc')->first();
            $FilePath1 = $entPosterTemplate->FilePath1;
            if ($memNumber != '' && $FilePath1 != '') {
                $mimg = public_path($FilePath1);
                $qrimg = '/uploads/qrcode/' . $memNumber . '.png';
                $qrimg1= public_path($qrimg);
                if(!file_exists($qrimg1)){ //二维码图片不存在,重新生成新的二维码图片
                    $drpId = DB::table('memberdrp')
                        ->where('MemNumber',$memNumber)
                        ->where('DeleteMark',1)
                        ->value('DRPID');
                    $url = 'http://wx.laohoulundao.com/parent/' . $drpId . '.html';
                    $qrcode = new BaconQrCodeGenerator;
                    $qrcode->format('png')->size(300)->generate($url, $qrimg1);
                }


                //海报模板
                $img1 = imageCreateFromPng($mimg);
                //会员二维码
                $img2 = imageCreateFromPng($qrimg1);
                imagecopymerge($img1, $img2, 205, 400, 0, 0, imagesx($img2), imagesy($img2), 100);
                imagepng($img1, $_SERVER['DOCUMENT_ROOT'] . '/uploads/posttemp/' . $memNumber . '.png');
                imagedestroy($img1);
                $url = '/uploads/posttemp/' . $memNumber . '.png';
            }
        } catch (Exception $e) {
            $url = '';
        }
        return $url;
    }

    /**
     * 生成模板
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function temoImgStore(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile'    => 'required',
            'id'        => 'required',
            'key'       => 'required'
        ];

        $messages = [
            'mobile.required'   => '2037',
            'id.required'       => '2037',
            'key.required'      => '2038'
        ];

        $mobile = $request->input('mobile');
        $key    = $request->input('key');
        $id     = $request->input('id');
        $params = ['mobile' => $mobile, 'key' => $key, 'id' => $id];

        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        $entMemberInfo = $this->memNumber($mobile, $key);


        if ($entMemberInfo) {
            $entMemberDRP = $this->memDRPNumber($entMemberInfo->MemNumber);


            if ($entMemberDRP) {
                $memNumber = $entMemberInfo->MemNumber;
                $entPosterTemplate = EntPosterTemplate::select('PosterTitle', 'FilePath1', 'PoTeID')
                    ->where('PoTeID', $id)
                    ->where('DeleteMark', 1)
                    ->where('IsShow', 1)
                    ->orderBy('ReleaseDate', 'desc')
                    ->first();


                $FilePath1 = $entPosterTemplate->FilePath1;

                if ($memNumber != '' && $FilePath1 != '') {
                    $mimg = $FilePath1;
                    $qrimg = '/uploads/qrcode/' . $memNumber . '.png';
                    //海报模板
                    $img1 = imageCreateFromPng($this->url . $mimg);
                    //会员二维码
                    $img2 = imageCreateFromPng($this->url2 . $qrimg);
                    imagecopymerge($img1, $img2, 205, 400, 0, 0, imagesx($img2), imagesy($img2), 100);
                    imagepng($img1, $_SERVER['DOCUMENT_ROOT'] . '/uploads/posttemp/' . $memNumber . '.png');
                    imagedestroy($img1);
                    $url = $this->urlapi . '/uploads/posttemp/' . $memNumber . '.png';
                    return response()->json(['message' => 'ok', 'code' => '200', 'tempurl' => $url]);
                }

            } else {
                return response()->json(['message' => $result, 'code' => '3039']);
            }
        } else {
            return response()->json(['message' => $result, 'code' => '3038']);
        }
    }

    /**
     * 会员信息
     * @param string $mobile
     * @param string $key
     * @return mixed
     */
    protected function memNumber($mobile = '', $key = '')
    {
        $entMemberInfo = EntMemberInfo::select('MemEndTime', 'FilePath1', 'YourName', 'MemNumber')
            ->where('States', '1')
            ->where('DeleteMark', '1')
            ->where('UserName', $mobile)
            ->where('AppKey', $key)->first();
        return $entMemberInfo;
    }

    /**
     * 合伙人详细
     * @param string $memNumber
     * @return mixed
     */
    protected function memDRPNumber($memNumber = '')
    {
        $entMemberDRP = EntMemberDRP::select('DRPID', 'SalesMoney', 'MemBalances', 'FinishMoney')
            ->where('DRPLevel', '1')
            ->where('DeleteMark', '1')
            ->where('MemNumber', $memNumber)
            ->first();
        return $entMemberDRP;
    }

    /**
     * 会员提现账号信息
     * @param string $cardNo
     * @param string $memNumber
     * @return mixed
     */
    protected function memPayCard($cardNo = '', $memNumber = '')
    {
        $entPayCard = EntPayCard::select('PaCaID', 'CardNo', 'YourName')->where('CardNo', $cardNo)->where('DeleteMark', '1')->where('MemNumber', $memNumber)->first();
        return $entPayCard;
    }
}